package com.app.teaware.goods;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.UnitListBean;
import com.app.teaware.bean.GoodsListBean;
import com.app.teaware.bean.GoodsListData;
import com.app.teaware.bean.GoodsWorks;
import com.app.teaware.bean.KWListBean;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.greendao.GreenDaoUtils;
import com.app.teaware.util.MyUtils;
import com.app.teaware.util.ReceiverUtils;
import com.app.teaware.util.UHFUtil;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.MathUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/***
 * 添加入库资料
 * **/
public class AddOrEditGoodsInfoActivity extends BasisActivity {

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    @BindView(R.id.edit_code)
    EditText edit_code;
    @BindView(R.id.edit_name)
    EditText edit_name;
    @BindView(R.id.edit_specs)
    EditText edit_specs;

    @BindView(R.id.text_unit)
    TextView text_unit;

    @BindView(R.id.edit_num)
    EditText edit_num;
    @BindView(R.id.text_weight)
    TextView text_weight;
    @BindView(R.id.edit_qrcode)
    EditText edit_qrcode;
    @BindView(R.id.text_gcd)
    TextView text_gcd;

    GoodsWorks works;
    String rfid;

    ArrayList<GoodsWorks> worksList = new ArrayList<>();
    String fTotalWeight = "0";    //整箱货品的重量，单位：kg

    UnitListBean unitListBean = null;   //所有货品单位


    public  static void toDetail(Activity context, int requst){
        Bundle extras = new Bundle();
        ActivityTool.skipActivityForResult(context, AddOrEditGoodsInfoActivity.class,extras,requst);
    }

    public  static void toEdit(Activity context,String rfid, int requst){
        Bundle extras = new Bundle();
        extras.putSerializable("rfid", rfid);
        ActivityTool.skipActivityForResult(context, AddOrEditGoodsInfoActivity.class,extras,requst);
    }


    public  static void toEdit(Activity context,GoodsWorks goodsWork, int requst){
        Bundle extras = new Bundle();
        extras.putSerializable("works", goodsWork);
        ActivityTool.skipActivityForResult(context, AddOrEditGoodsInfoActivity.class,extras,requst);
    }


    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.add_goods_info_activity);
        setTitle("编辑入库资料");
        setTitleLeftButton(null);

        setTitleLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(worksList != null && worksList.size()>0){
                    Intent data = new Intent();
                    data.putExtra("list", worksList);
                    setResult(Constants.SCANDATASULT,data);
                }
                finish();
            }
        });


        //监测数量变化事件
        edit_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable edit) {
                //edit  输入结束呈现在输入框中的信息
                if(resultGoodsData != null && !edit_num.getText().toString().isEmpty() && !text_unit.getText().toString().isEmpty()) {
                    //规格字符串拼接
                    edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                    //重量自动计算
                    fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                    text_weight.setText(fTotalWeight);
                }
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        works = (GoodsWorks) getIntent().getSerializableExtra("works");
        rfid= getIntent().getStringExtra("rfid");

        edit_qrcode.setEnabled(false);
        if(works != null){
            edit_qrcode.setText(works.getRfid());
            text_unit.setText(works.getGun());
            edit_num.setText(works.getGnu());
            getResultGoodsDataByGid(works.getGid());
        }else if(!TextUtils.isEmpty(rfid)){
            edit_qrcode.setText(rfid);
            getGoodsDataByEpcId(rfid);
        }
        //ice 3 获取所有单位
        unitListBean = GreenDaoUtils.getUnitListBean();
    }


    @OnClick(R.id.view_price)
    void UnitBtn() {
        if(unitListBean == null) return;
        new QMUIDialog.MenuDialogBuilder(mContext)
                .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                .addItems(unitListBean.getAllUnits(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        text_unit.setText(unitListBean.getAllUnits()[which]);
                        if(resultGoodsData != null && !edit_num.getText().toString().isEmpty() && !text_unit.getText().toString().isEmpty()) {
                            //规格字符串拼接
                            edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                            //重量自动计算
                            fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                            text_weight.setText(fTotalWeight);
                        }
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }


    private void getResultGoodsDataByGid(String gid){
        showLoading();
        MyParams params = new MyParams();
        params.put("aid", LoginBean.getInstance().getAcode());
        params.put("gid", gid);
        MyHttpUtils.get(Constants.URL_GOODS_SELECT_ONE_BY_GID, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        GoodsListBean listBean = (GoodsListBean) result;
                        if(listBean!= null && listBean.getList().size()>0){
                            resultGoodsData = listBean.getList().get(0);
                            edit_code.setText(resultGoodsData.getGno());
                            edit_name.setText(resultGoodsData.getGna());
                            text_gcd.setText(resultGoodsData.getGcd());
                            edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                            //重量自动计算
                            fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                            text_weight.setText(fTotalWeight);
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        httpIsFinish = true;
                        hideLoading();
                    }
                },
                0, GoodsListBean.class);


    }



    @OnClick({R.id.btn_code,R.id.btn_scan,R.id.btn_specs})
    void btnOnclick(){
        ActivityTool.skipActivityForResult(mContext,GoodsDataActivity.class,Constants.GOODSDATARESULT);
    }


    private boolean httpIsFinish = true;
    private GoodsListData goodsData;
    private void getGoodsDataByEpcId(String rfid){
        if(!httpIsFinish) return;
        httpIsFinish = false;

        showLoading();
        MyParams params = new MyParams();
        params.put("aid", LoginBean.getInstance().getAcode());
        params.put("rfid",rfid);

        MyHttpUtils.get(Constants.URL_WORK_SELECT_BY_RFID, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        GoodsListBean listBean = (GoodsListBean) result;
                        if(listBean != null && listBean.getList().size()>0){
                            goodsData = listBean.getList().get(0);
                            edit_num.setText(goodsData.getGnu());
                            text_unit.setText(goodsData.getGun());
                            getResultGoodsDataByGid(goodsData.getGid());
                          }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        hideLoading();
                    }

                    @Override
                    public void onFinish(int httpWhat) {

                    }
                },
                0, GoodsListBean.class);

    }



    GoodsListData resultGoodsData = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.GOODSDATARESULT){
            resultGoodsData = (GoodsListData) data.getSerializableExtra("data");
            if(resultGoodsData != null){
                edit_code.setText(resultGoodsData.getGno());
                edit_name.setText(resultGoodsData.getGna());

                if(resultGoodsData != null && !edit_num.getText().toString().isEmpty() && !text_unit.getText().toString().isEmpty()) {
                    //规格字符串拼接
                    edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                    //重量自动计算
                    fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                    text_weight.setText(fTotalWeight);
                }
            }
        }
    }

    //ice 硬件相关，rfid读卡成功通知
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();

            switch (action){
                case Constants.ACTION_UHF_RESULT_SEND:
                    Parcelable[] tagInfos = intent.getParcelableArrayExtra(Constants.EXTRA_TAG_INFO);
                    String qrcode = UHFUtil.getEPCId(tagInfos).trim().toUpperCase(Locale.ROOT);

                    if(!TextUtils.isEmpty(qrcode)) {
                        edit_qrcode.setText(qrcode);
                        getGoodsDataByEpcId(qrcode);
                    }
                    break;

                case Constants.ACTION_SCANNER_RESULT_SEND:
                    final  String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
                    final  String scanResult_2 = intent.getStringExtra("SCAN_BARCODE2");
                    final  int barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE",-1);
                    final String scanStatus = intent.getStringExtra("SCAN_STATE");
                    if("ok".equals(scanStatus)) {
                        System.out.println("ice 硬件扫码结果：" + scanResult_1.trim());
                    }
                    break;
            }


        }//end onReceiver
    };

    @Override
    protected void onPause() {
        super.onPause();
        ReceiverUtils.unRegisterReceiver(mContext,mResultReceiver);
        UHFUtil.setMinPowerDB();
        UHFUtil.allTriggerModeOpen();
    }


    @Override
    protected void onResume() {
        super.onResume();
        ReceiverUtils.registerUHFAndScannerReceiver(mContext,mResultReceiver);
    }

    @OnClick(R.id.btn_clear)
    void btnClear(){
        edit_name.getText().clear();
        edit_specs.getText().clear();
        edit_num.getText().clear();
        text_weight.setText("");
        text_gcd.setText("");
        edit_qrcode.getText().clear();  //清空显示信息
    }

    private boolean isOk = false;
    @OnClick(R.id.btn_add)
    void btnAdd(){
        isOk = false;
        try {
            if (TextUtils.isEmpty(edit_code.getText().toString())) {
                showToast("单号不能为空");
                return;
            }
            if (TextUtils.isEmpty(edit_num.getText().toString())) {
                showToast("数量不能为空");
                return;
            }
            if (Double.valueOf(edit_num.getText().toString()) == 0) {
                showToast("数量不为0");
                return;
            }
            if (TextUtils.isEmpty(text_weight.getText().toString())) {
                showToast("重量不能为空");
                return;
            }

            if (Double.valueOf(text_weight.getText().toString()) == 0) {
                showToast("重量不为0");
                return;
            }
            if (TextUtils.isEmpty(edit_qrcode.getText().toString())) {
                showToast("箱码不能为空");
                return;
            }
            GoodsWorks  works = new GoodsWorks();
            works.setAid(LoginBean.getInstance().getAcode());
            works.setBfs(MyUtils.getHomeSelectId());            //1工单/2领料/3退料/4入库
            if(goodsData != null){
                works.setCid(goodsData.getCid());
                works.setSid(goodsData.getSid());
                works.setWms(goodsData.getWms()); //库位
            }

            works.setGid(resultGoodsData.getGid());              //货品id
            works.setGna(edit_name.getText().toString());       //货品名称
            works.setGno(edit_code.getText().toString());       //货品编码
            works.setGun(text_unit.getText().toString());       //整件单位
            works.setGnu(edit_num.getText().toString());        //包装数量
            works.setGsp(edit_specs.getText().toString());      //货品规格
            works.setGunp(resultGoodsData.getGun());       //最小单位
            works.setGwt(text_weight.getText().toString());     //整件重量
            works.setGwtp(""+resultGoodsData.getGwt());
            works.setMdt(TimeUtils.getCurrentTimeByFormat("yyyy-MM-dd"));
            works.setRfid(edit_qrcode.getText().toString().trim()); //箱码
            works.setBwf(resultGoodsData.getBwf());           //纸箱净重
            worksList.add(works);
            edit_code.getText().clear();
            edit_name.getText().clear();
            edit_specs.getText().clear();
            edit_num.getText().clear();
            text_weight.setText("");

            edit_qrcode.getText().clear();  //清空显示信息
            isOk = true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "保存失败！", Toast.LENGTH_SHORT).show();
        }
    }


    @OnClick(R.id.btn_submit)
    void btnSubmit(){
        btnAdd();
        if(isOk){
            Intent data = new Intent();
            data.putExtra("list", worksList);
            setResult(Constants.SCANDATASULT,data);
            finish();
        }
    }

}
